/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { assetManager, error, resources } from 'cc';
import { request, RequestOptions } from './request';
import { path } from './utils';
import { loadRemote } from './asset';
import { assetLoader } from './asset-loader';
import { JSB } from 'cc/env';
import { splitPackPath } from './utils/path';
import { variable } from './variable';

const TAG = 'lcc/core/request-preset.ts';

/**
 * @zh
 * 注册 resources 协议，用于从resources包加载资源
 * URL格式：resources[-资源类型][|处理管道[|...]]://<包内文件相对路径>
 *              子协议为资源类型，可选。也可以通过文件名称推导资源路径
 * 实例：   request.get('resources://test.json') 加载resources包中的test.json文件
 */
request.register('resources', {
    async get(mainproto: string, subproto: string, path_: string, options?: RequestOptions) {
        // 解析路径
        let [assetPath, extname] = path.splitext(path_);

        // 资源类型为子协议或者后缀名
        let assetType = subproto || extname;
        if (!assetType) {
            error(TAG, `resources asset '${path_}' type unknown`);
            return null;
        }
        assetType = assetType.toLowerCase();

        return assetLoader.load(assetPath, assetType, resources);
    }
});

/**
 * @zh
 * 注册 asset 协议，用于从bundle包加载资源
 * URL格式：asset[-资源类型][|处理管道[|...]]://<包名称>/<包内文件相对路径>
 *              子协议为资源类型，可选。也可以通过文件名称推导资源路径
 * 实例：request.get('asset://resources/test.json') 加载resources包中的test.json文件
 */
request.register('asset', {
    async get(mainproto: string, subproto: string, path1: string, options?: RequestOptions) {
        // 解析路径
        let [packPath, extname] = path.splitext(path1);

        // 资源类型为子协议或者后缀名
        let assetType = subproto || extname;
        if (!assetType) {
            error(TAG, `asset '${path1}' type unknown`);
            return null;
        }
        assetType = assetType.toLowerCase();

        // 解析包路径
        let [packName, assetPath] = splitPackPath(packPath);

        let bundle = assetManager.getBundle(packName);
        if (!bundle) {
            error(TAG, `bundle ${packName} not found`);
            return null;
        }

        return assetLoader.load(assetPath, assetType, bundle);
    }
});

/**
 * @zh
 * 注册 remote 协议，用于从远程服务器加载资源，一般是图片资源。<br/>
 * URL格式：remote<-协议类型>[|处理管道[|...]]://<网络URL路径>
 * 实例：request.get('remote-http://localhost:8080/test.png'), 子协议为具体HTTP协议
 */
request.register('remote', {
    async get(mainproto: string, subproto: string, path: string, options?: RequestOptions) {
        return loadRemote(`${subproto}://${path}`);
    }
});

if (JSB) {
    /**
     * @zh
     * 注册 file 协议，用于操作本地文件。<br/>
     * URL格式：file[|处理管道[|...]]://<本地文件路径>
     * 实例：request.get(`file://${jsb.fileUtils.getWritablePath()}/test.txt`) 读取文件
     *      request.post(`file://${jsb.fileUtils.getWritablePath()}/test.txt`, "测试文件内容") 写入文件
     *      request.delete(`file://${jsb.fileUtils.getWritablePath()}/test.txt`) 删除文件
     */
    request.register('file', {
        async get(mainproto: string, subproto: string, path: string, options?: RequestOptions) {
            return jsb.fileUtils.getStringFromFile(variable.formatString(path));
        },
        async post(mainproto: string, subproto: string, path: string, data: any, options?: RequestOptions) {
            return jsb.fileUtils.writeStringToFile(String(data), variable.formatString(path));
        },
        async delete(mainproto: string, subproto: string, path: string, options?: RequestOptions) {
            return jsb.fileUtils.removeFile(variable.formatString(path));
        }
    });
}
